package cn.muqingfeng.bbs.ui;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.to.Column;
import cn.muqingfeng.api.to.SendResTO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.bbs.ui.widget.AvatarPickerPopup;
import cn.muqingfeng.util.AccountManager;
import cn.muqingfeng.util.Code;
import cn.muqingfeng.util.ViewHolder;

import com.google.gson.Gson;

public class SendArticleActivity extends BaseActivity implements OnClickListener, OnLongClickListener {
	private static final List<Column> COLUMNS = new ArrayList<Column>();
	static {
		COLUMNS.add(new Column("微信分享", 65));
		COLUMNS.add(new Column("热点新闻", 187));
		COLUMNS.add(new Column("图说天下", 74));
		COLUMNS.add(new Column("故事会", 183));
		COLUMNS.add(new Column("旅游度假", 57));
		COLUMNS.add(new Column("小说阅读", 114));
		COLUMNS.add(new Column("时尚家居", 56));
		COLUMNS.add(new Column("美食分享", 69));
		COLUMNS.add(new Column("美女图片", 59));
		COLUMNS.add(new Column("青春文学", 184));
		COLUMNS.add(new Column("小清新图", 78));
		COLUMNS.add(new Column("笑话趣图", 92));
		COLUMNS.add(new Column("星座物语", 49));
		COLUMNS.add(new Column("唯美婚纱", 60));
		COLUMNS.add(new Column("厦门生活", 135));
		// COLUMNS.add(new Column("微视", 88));
		// COLUMNS.add(new Column("高清电影", 2));
	}
	private static Object LOCK = new Object();
	private EditText mTitleView;
	private EditText mContentView;
	private RecyclerView mRecyclerView;
	private ImageAdapter mAdapter;
	private AvatarPickerPopup avatarPickerPopup;
	private boolean isSending = false;
	private ProgressDialog mDialog;
	private TextView mLanmuView;
	private ImageView mCodeView;
	private EditText mInputCodeView;
	private Code mCode;
	private Column mColumn;
	private HttpPost mUploadRequest;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_acticle);
		setupViews();
	}

	private void setupViews() {
		findViewById(R.id.back).setOnClickListener(this);
		mTitleView = (EditText) findViewById(R.id.title);
		mContentView = (EditText) findViewById(R.id.content);
		findViewById(R.id.send).setOnClickListener(this);
		mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		mRecyclerView.setLayoutManager(layoutManager);
		mAdapter = new ImageAdapter();
		mRecyclerView.setAdapter(mAdapter);
		mLanmuView = (TextView) findViewById(R.id.column);
		findViewById(R.id.choose_fid).setOnClickListener(this);
		mCodeView = (ImageView) findViewById(R.id.code);
		mCodeView.setOnClickListener(this);
		mInputCodeView = (EditText) findViewById(R.id.code_input);
		mCode = Code.getInstance(getApplicationContext());
		changeCode();
	}

	private void changeCode() {
		Bitmap bitmap = mCode.createBitmap();
		mCodeView.setImageBitmap(bitmap);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.send:
			send();
			break;
		case R.id.image:
			ImageView imageView = (ImageView) v;
			int position = Integer.parseInt(String.valueOf(imageView.getTag()));
			if (mAdapter.getItemCount() - 1 == position) {
				hideSystemKeyBoard(getApplicationContext(), mContentView);
				addImage();
			}
			break;
		case R.id.code:
			changeCode();
			break;
		case R.id.choose_fid:
			showChoosColumnDialog();
			break;
		default:
			break;
		}
	}

	private AlertDialog mColumnDialog;

	private synchronized void showChoosColumnDialog() {
		if (mColumnDialog != null && mColumnDialog.isShowing())
			return;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("选择栏目");
		builder.setAdapter(new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = View.inflate(getApplicationContext(), R.layout.column_item, null);
				}
				TextView text = ViewHolder.get(convertView, R.id.text);
				text.setText(COLUMNS.get(position).getName());
				return convertView;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return COLUMNS.get(position);
			}

			@Override
			public int getCount() {
				return COLUMNS.size();
			}
		}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mColumn = COLUMNS.get(which);
				mLanmuView.setText(mColumn.getName());
			}
		});
		builder.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				mColumn = COLUMNS.get(position);
				mLanmuView.setText(mColumn.getName());
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		mColumnDialog = builder.create();
		mColumnDialog.show();
	}

	private void send() {
		synchronized (LOCK) {
			if (isSending) {
				return;
			}
			final String title = mTitleView.getText().toString();
			if (TextUtils.isEmpty(title) || title.length() < 4) {
				Toast.makeText(getApplicationContext(), "标题(必填，最少4个字)", Toast.LENGTH_SHORT).show();
				return;
			}
			final String content = mContentView.getText().toString();
			if (TextUtils.isEmpty(content)) {
				Toast.makeText(getApplicationContext(), "请输入正文内容", Toast.LENGTH_SHORT).show();
				return;
			}
			if (mColumn == null) {
				Toast.makeText(getApplicationContext(), "请选择栏目", Toast.LENGTH_SHORT).show();
				return;
			}
			String code = mInputCodeView.getText().toString();
			if (TextUtils.isEmpty(code)) {
				Toast.makeText(getApplicationContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
				return;
			}
			if (!mCode.getCode().equalsIgnoreCase(code)) {
				Toast.makeText(getApplicationContext(), "验证码不匹配", Toast.LENGTH_SHORT).show();
				return;
			}
			isSending = true;
			showDialog();
			new AsyncTask<Void, Void, SendResTO>() {

				protected void onPreExecute() {
					showDialog();
				};

				@Override
				protected SendResTO doInBackground(Void... params) {
					try {
						String requestUrl = UriHelper.getSendArticleUrl(mColumn.getId());
						AndroidHttpClient httpclient = AndroidHttpClient.newInstance(RequestHelper.UA, getApplicationContext());
						try {
							mUploadRequest = new HttpPost(requestUrl);
							List<String> paths = mAdapter.getPaths();
							MultipartEntity reqEntity = new MultipartEntity();
							if (!paths.isEmpty()) {
								for (int i = 0; i < paths.size(); i++) {
									String path = paths.get(i);
									FileBody bin = new FileBody(new File(path));
									reqEntity.addPart("upload" + (i + 1), bin);
								}
							}

							UserTO user = AccountManager.getUser(getApplicationContext());
							mUploadRequest.addHeader(UriHelper.PARAMS_HEADER_USERNAME, user.getUsername());
							mUploadRequest.addHeader(UriHelper.PARAMS_HEADER_PASSWORD, AccountManager.getPassword(getApplicationContext()));
							Charset charset = Charset.forName("UTF-8");
							reqEntity.addPart(UriHelper.PARAMS_SUBJECT, new StringBody(title, charset));
							reqEntity.addPart(UriHelper.PARAMS_MESSAGE, new StringBody(content, charset));
							mUploadRequest.setEntity(reqEntity);
							HttpResponse response = httpclient.execute(mUploadRequest);
							HttpEntity resEntity = response.getEntity();
							String result = EntityUtils.toString(resEntity);
							if (!TextUtils.isEmpty(result)) {
								Gson gson = new Gson();
								return gson.fromJson(result, SendResTO.class);
							}
						} finally {
							httpclient.close();
							mUploadRequest = null;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(SendResTO result) {
					if (!isDestroied()) {
						dismissDialog();
						if (result == null) {
							Toast.makeText(getApplicationContext(), "发送失败！", Toast.LENGTH_SHORT).show();
						} else {
							String message = result.getMessage();
							Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
							if (result.isSuccess()) {
								mTitleView.setText("");
								mContentView.setText("");
								mAdapter.clear();
								changeCode();
							}
						}
					}
				}
			}.execute();
		}
	}

	@Override
	public boolean onLongClick(View v) {
		switch (v.getId()) {
		case R.id.image:
			ImageView imageView = (ImageView) v;
			int position = Integer.parseInt(String.valueOf(imageView.getTag()));
			if (mAdapter.getItemCount() - 1 != position) {
				mAdapter.remove(position);
			}
			break;
		default:
			break;
		}
		return false;
	}

	private void addImage() {
		avatarPickerPopup = new AvatarPickerPopup(this);
		avatarPickerPopup.setCrop(false);
		ViewGroup decor = (ViewGroup) getWindow().getDecorView();
		avatarPickerPopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		// 根据上面发送过去的请求码来区别
		switch (requestCode) {
		case Constants.REQUEST_CODE_PICK_PHOTO:
		case Constants.REQUEST_CODE_TAKE_PHOTO:
			String path = data.getStringExtra("CropperPhotoPath");
			mAdapter.add(path);
			mAdapter.notifyDataSetChanged();
			break;
		default:
			break;
		}
	}

	private class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {
		private List<String> mPaths = new ArrayList<String>();

		public List<String> getPaths() {
			return mPaths;
		}

		@Override
		public int getItemCount() {
			return mPaths.size() + 1;
		}

		public void add(String path) {
			mPaths.add(path);
		}

		public void clear() {
			mPaths.clear();
			notifyDataSetChanged();
		}

		public void remove(int position) {
			mPaths.remove(position);
			mAdapter.notifyDataSetChanged();
		}

		@Override
		public void onBindViewHolder(ImageHolder holder, int position) {
			if (getItemCount() - 1 == position) {
				holder.getImageView().setImageResource(R.drawable.image_add);
			} else {
				String path = mPaths.get(position);
				holder.getImageView().setImageURI(Uri.fromFile(new File(path)));
			}
			holder.getImageView().setTag(position);
		}

		@Override
		public ImageHolder onCreateViewHolder(ViewGroup parent, int position) {
			View view = View.inflate(parent.getContext(), R.layout.image_item, null);
			return new ImageHolder(view);
		}

	}

	class ImageHolder extends RecyclerView.ViewHolder {
		private ImageView mImageView;

		public ImageHolder(View itemView) {
			super(itemView);
			mImageView = (ImageView) itemView.findViewById(R.id.image);
			mImageView.setOnClickListener(SendArticleActivity.this);
			mImageView.setOnLongClickListener(SendArticleActivity.this);
		}

		public ImageView getImageView() {
			return mImageView;
		}
	}

	public void hideSystemKeyBoard(Context mcontext, View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	private void showDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			return;
		}
		mDialog = new ProgressDialog(this);
		mDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				isSending = false;
			}
		});
		mDialog.setMessage("正在发送，请稍等...");
		mDialog.show();
	}

	private void dismissDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}
}
